
const { init } = require('./../../wxCloudClientSDK.umd.js')
// 指定云开发环境 ID
wx.cloud.init({
  env: "cloud1-9gel6ndh8e555155", // 当前的云开发环境 ID
});

const client = init(wx.cloud);


Page({
  data: {
    goodsList: [
      /*{
        id: 1,
        name: '【儿童涂氟】全口涂氟套餐/呵护儿牙',
        image: '/images/goods1.jpg',
        price: 28785,
        count: 1
      },*/
    ],
    formData: {
      name: '',
      phone: '',
      remark: '',
      patient: ''
    },
    patientList: [
      { id: 1, name: '张三' },
      { id: 2, name: '李四' },
      { id: 3, name: '王五' }
    ],
    showPatientPicker: false,
    totalPrice: 0,
    freight: 0,
    payAmount: 0
  },

  onLoad: function() {
    this.loadData();
    this.calculatePrice();
  },

  /* 加载数据 */
  loadData: function() {

    const cartSelectedItems = wx.getStorageSync('cartSelectedItems');

    console.log("goodsList: ", cartSelectedItems);

    this.setData({
      goodsList: cartSelectedItems
    });
    
  },

  // 计算价格
  calculatePrice: function() {
    let totalPrice = this.data.goodsList.reduce((sum, item) => {
      return sum + item.price * item.quantity;
    }, 0);
    
    this.setData({
      totalPrice: totalPrice.toFixed(2),
      payAmount: (totalPrice + this.data.freight).toFixed(2)
    });
  },

  // 输入姓名
  inputName: function(e) {
    this.setData({
      'formData.name': e.detail.value
    });
  },

  // 输入手机号
  inputPhone: function(e) {
    this.setData({
      'formData.phone': e.detail.value
    });
  },

  // 输入备注
  inputRemark: function(e) {
    this.setData({
      'formData.remark': e.detail.value
    });
  },

  // 显示购买人选择器
  showPatientPicker: function() {
    this.setData({
      showPatientPicker: true
    });
  },

  // 隐藏购买人选择器
  hidePatientPicker: function() {
    this.setData({
      showPatientPicker: false
    });
  },

  // 选择购买人
  selectPatient: function(e) {
    const patient = e.currentTarget.dataset.patient;
    this.setData({
      'formData.patient': patient.name,
      showPatientPicker: false
    });
  },

  // 提交订单
  submitOrder: function() {
    const { formData } = this.data;
    
    // 表单验证
    if (!formData.name) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return;
    }
    if (!formData.phone) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      });
      return;
    }
    if (!/^1\d{10}$/.test(formData.phone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      });
      return;
    }
    if (!formData.patient) {
      wx.showToast({
        title: '请选择购买人',
        icon: 'none'
      });
      return;
    }

    // 显示加载提示
    wx.showLoading({
      title: '提交中...',
      mask: true
    });

    // TODO: 调用提交订单接口
    /*
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            wx.navigateBack();
          }, 2000);
        }
      });
    }, 1500);
    */

   this.saveOrderInfo();

  },

  /* 保存订单信息 */
  saveOrderInfo: function() {
    const userId = 1;     // 当前登录用户ID
    const totalPrice = this.data.totalPrice;  // 商品金额
    const fee = this.data.freight;  // 运费
    const payAmount = this.data.payAmount;  // 需支付金额
    const status = "1";  // 待付款
    const createTime = Date.now();  // 下单时间

    const { formData } = this.data;

    const username = formData.name;  // 姓名
    const phone = formData.phone;  // 手机号
    const remark = formData.remark;  // 备注
    const buyerName = formData.patient;  // 购买人姓名

    const {data} = client.models.order_info.create({
      data: {
        userId: userId,
        totalPrice: totalPrice,
        fee: fee,
        payAmount: payAmount,
        status: status,
        createTime: createTime,
        username: username,
        phone: phone,
        remark: remark,
        buyerName: buyerName,
      }
    }).then(res => {
      console.log("order_info data: ", res.data.id);

      this.saveOrderItemInfos(res.data.id);

      wx.hideLoading();
    }).catch(res => {
      console.log("err order_info data: ", res);

      wx.hideLoading();
    });

  },

  saveOrderItemInfos: function(orderId) {
    const cartSelectedItems = wx.getStorageSync('cartSelectedItems');
    
    var orderItems = [];

    cartSelectedItems.forEach(item => {
      orderItems = orderItems.concat({
        orderInfoId: orderId,
        productId: item.id,
        productName: item.name,
        price: item.price,
        quantity: item.quantity,
        totalPrice: item.price * item.quantity,
      });
    });
    
  
    const { data } = client.models.order_item_info.createMany({
      data: orderItems
    }).then(res => {
      console.log("save order_item_info: ", res);

      wx.hideLoading();

      wx.navigateTo({
        url: `/page/payment/index?orderId=${orderId}`,
      })

    }).catch(res => {
      console.log("err save order_item_info:", res);

      wx.hideLoading();
    });

    
  },


}); 